from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import json
import requests
import time
from bs4 import BeautifulSoup
import time
import re
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []

    lis = response.json()[0]["documents"]

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li["Title1"]
        except:
            pass
        try:
            tempData["titleHref"] = "http://www.cnbksy.com/search/detail/" + li["Id"]
        except:
            pass
        try:
            tempData["author"] = li["AU_F"]
        except:
            pass
        try:
            tempData["publishTime"] = li["Year"]
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword,cookies):


    headers = {
        'Origin': 'http://www.cnbksy.com',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Referer': 'http://www.cnbksy.com/search?searchContent=cell&categories=1,2&type=1',
        'X-Requested-With': 'XMLHttpRequest',
        'Connection': 'keep-alive',
    }

    params = (
        ('_csrf', cookies["XSRF-TOKEN"]),
    )

    data = '{"author":null,"clc":null,"searchContent":"' + keyword + '","categories":"1,2","types":"1","isRestart":true,"pageCount":"10","asc":"false","relative":"true","facets":[]}'

    response = requests.post('http://www.cnbksy.com/search/query', headers=headers, params=params, cookies=cookies,
                             data=data)

    allData = formData(response)

    return allData

def getCookies():

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    s = requests.session()
    response = s.get('http://www.cnbksy.com/home', headers=headers)
    c = requests.cookies.RequestsCookieJar()  # 利用RequestsCookieJar获取

    cookies = s.cookies.get_dict()

    return cookies


def index(request):
    cookies = getCookies()

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0],cookies)

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")